﻿using InParkRedemptionAPI.DataAccess;
using InParkRedemptionAPI.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebAPI.Common.Attributes;
using WebAPI.Common;
using WebAPI.Controllers;
using WebAPI.Models;
using WebAPI.Util;
using Microsoft.AspNetCore.Authorization;
using System.Linq;
using RapidSalesAdminPortalAPI.DataAccess;

namespace InParkRedemptionAPI.Controllers
{
    //[Authorize]
    //[Route("api/[controller]")]
    //[ApiController]
    //public class FrIpRedemptionPointController : ParentController
    //{
    //    private readonly Rdm_AdmPortalContext _db;
    //    private readonly IConfiguration _configuration;
    //    private readonly ILogUtility _logUtility;
    //    private readonly ILogger _logger;
    //    private readonly IDataProtectorUtility _dataProtectorUntility;
    //    public FrIpRedemptionPointController(Rdm_AdmPortalContext context, IConfiguration configuration, ILogUtility logUtility, ILogger<FrIpRedemptionPointController> logger, IDataProtectorUtility dataProtectorUntility)
    //    {
    //        _db = context;
    //        _configuration = configuration;
    //        _logUtility = logUtility; // sample code for DI of common utility class
    //        _logger = logger;
    //        _dataProtectorUntility = dataProtectorUntility;
    //    }

    //    [HttpPost("GetRedemptionPointList")]
    //    public async Task<ActionResult<ResultMsg>> GetRedemptionPointList([FromBody] GetRedemptionPointListRequest requestModel)
    //    {
    //        var resultMsg = new ResultMsg();
    //        try
    //        {
    //            IQueryable<FrIpRedemptionPoint> paComont = _db.FrIpRedemptionPoints.Include(x => x.OperationArea).Where(x => x.IsDelete == false)
    //                .AsQueryable();
    //            if (!string.IsNullOrWhiteSpace(requestModel.Enable))
    //                paComont = paComont.Where(x => x.Enable.ToString() == requestModel.Enable);
    //            if (!string.IsNullOrWhiteSpace(requestModel.Code))
    //                paComont = paComont.Where(x => x.Code.Contains(requestModel.Code));
    //            if (!string.IsNullOrWhiteSpace(requestModel.Name))
    //                paComont = paComont.Where(x => x.Name.Contains(requestModel.Name));
    //            if (!string.IsNullOrWhiteSpace(requestModel.Description))
    //                paComont = paComont.Where(x => x.Description.Contains(requestModel.Description));
    //            if (!string.IsNullOrWhiteSpace(requestModel.OperationArea))
    //                paComont = paComont.Where(x => x.OperationArea.DefaultSetValue.Contains(requestModel.OperationArea));

    //            var paData = paComont.ToList().Select(x => new GetRedemptionPointListResponse()
    //            {
    //                Id = x.Id,
    //                Code = x.Code,
    //                Name = x.Name,
    //                OperationArea = x.OperationArea.DefaultSetValue,
    //                OperationAreaId= x.OperationAreaId,
    //                Description = x.Description,
    //                Enable = x.Enable,
    //                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
    //                UpdateDate = x.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss"),
    //                CreateUser = UserNameQuery(x.CreateUser),
    //                UpdateUser = UserNameQuery(x.UpdateUser)
    //            }).AsQueryable();

    //            if (!string.IsNullOrWhiteSpace(requestModel.Field) && paComont.Count() > 0)
    //                paData = DBHelper.DataSorting(paData, requestModel.Field, requestModel.Order);
    //            else
    //                paData = DBHelper.DataSorting(paData, "CreateDate", "desc");

    //            var RedemptionPoint = await BasePageOutputExtensions.ToPagedListAsync(paData.ToList(), requestModel.Page, requestModel.PageSize);

    //            return resultMsg.SetResultMsg(
    //                 (int)ResultCode.Success,
    //                 HelperUtility.GetDescription(ResultCode.Success),
    //                 RedemptionPoint);
    //        }
    //        catch (Exception ex)
    //        {
    //            _logger.LogError(ex.Message);
    //            return resultMsg.SetResultMsg(
    //                 (int)ResultCode.ErrorOnRequestUnMarshalling,
    //                 HelperUtility.GetDescription(ResultCode.ErrorOnRequestUnMarshalling),
    //                 null);
    //        }
    //    }

    //    [HttpGet("{id}")]
    //    public async Task<ActionResult<ResultMsg>> GetRedemptionPoint(Guid id)
    //    {
    //        var resultMsg = new ResultMsg();
    //        try
    //        {
    //            FrIpRedemptionPoint pa = await _db.FrIpRedemptionPoints.Include(x => x.OperationArea).FirstOrDefaultAsync(x => x.Id == id);
    //            var productIds = await _db.FrIpRedemptionPointProducts.Where(x => x.RedemptionPointId == id).Select(x=>x.ProductId).ToListAsync();
    //            if (pa == null)
    //            {
    //                return resultMsg.SetResultMsg(
    //                     (int)ResultCode.UserNotFound,
    //                     HelperUtility.GetDescription(ResultCode.UserNotFound),
    //                     null);
    //            }

    //            var RedemptionPoint = new GetRedemptionPointListResponse()
    //            {
    //                Id = pa.Id,
    //                Code = pa.Code,
    //                Name = pa.Name,
    //                OperationArea = pa.OperationArea.DefaultSetValue,
    //                OperationAreaId = pa.OperationAreaId,
    //                ProductIds = productIds,
    //                HasProduct = productIds.Count() > 0 ? true : false,
    //                Description = pa.Description,
    //                Enable = pa.Enable,
    //                CreateDate = pa.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
    //                UpdateDate = pa.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss"),
    //                CreateUser = UserNameQuery(pa.CreateUser),
    //                UpdateUser = UserNameQuery(pa.UpdateUser)
    //            };
    //            return resultMsg.SetResultMsg(
    //                 (int)ResultCode.Success,
    //                 HelperUtility.GetDescription(ResultCode.Success),
    //                 RedemptionPoint);
    //        }
    //        catch (Exception ex)
    //        {
    //            _logger.LogError(ex.Message);
    //            return resultMsg.SetResultMsg(
    //                 (int)ResultCode.ErrorOnRequestUnMarshalling,
    //                 HelperUtility.GetDescription(ResultCode.ErrorOnRequestUnMarshalling),
    //                 null);
    //        }
    //    }

    //    [HttpPost("GetRedemptionPointProduct")]
    //    public async Task<ActionResult<ResultMsg>> GetRedemptionPointProduct([FromBody] GetRedemptionPointProductRequest requestModel)
    //    {
    //        var resultMsg = new ResultMsg();
    //        try
    //        {
    //            FrIpRedemptionPoint pa = await _db.FrIpRedemptionPoints.FirstOrDefaultAsync(x => x.Id == requestModel.RedemptionPointId);
    //            if (pa == null)
    //            {
    //                return resultMsg.SetResultMsg(
    //                     (int)ResultCode.NoDataFound,
    //                     HelperUtility.GetDescription(ResultCode.NoDataFound),
    //                     null);
    //            }

               

    //            var products = await _db.FrIpDataDictionaries.Include(x => x.FrIpRedemptionPointProducts).Where(x => x.Enable && x.CodeItemName.Equals("RedemptionPoint") && x.ItemTypeName.Equals("Products"))
    //                .Select(x => new GetRedemptionPointProductListResponse
    //                {
    //                    ProductId = x.Id,
    //                    Function = x.CodeItemName,
    //                    ProductCode = x.DefaultSetValue,
    //                    ProductName = x.Description,
    //                    IsCheck = x.FrIpRedemptionPointProducts.Any(x => x.RedemptionPointId == requestModel.RedemptionPointId)
    //                }).OrderBy(x=>x.ProductCode).ToListAsync();


    //            if (!string.IsNullOrWhiteSpace(requestModel.FieldName))
    //            {
    //                products = products.Where(x => x.ProductName.Contains(requestModel.FieldName) || x.ProductCode.Contains(requestModel.FieldName)).OrderBy(x => x.ProductCode).ToList();
    //            }

    //            //var products = await _db.FrIpRedemptionPointProducts
    //            //    .Join(_db.FrIpDataDictionaries,
    //            //    a=>a.ProductId,
    //            //    b=>b.Id,
    //            //    (a, b)=> new { a, b })
    //            //    .Where(x => x.a.RedemptionPointId == RedemptionPointId)
    //            //    .Select(x => new GetRedemptionPointProductListResponse
    //            //    { 
    //            //        ProductId = x.a.ProductId,
    //            //        Function = x.b.CodeItemName,
    //            //        ProductCode = x.b.DefaultSetValue,
    //            //        ProductName = x.b.Description,
    //            //        IsCheck = true
    //            //    }).ToListAsync();

    //            return resultMsg.SetResultMsg(
    //                 (int)ResultCode.Success,
    //                 HelperUtility.GetDescription(ResultCode.Success),
    //                 products);
    //        }
    //        catch (Exception ex)
    //        {
    //            _logger.LogError(ex.Message);
    //            return resultMsg.SetResultMsg(
    //                 (int)ResultCode.ErrorOnRequestUnMarshalling,
    //                 HelperUtility.GetDescription(ResultCode.ErrorOnRequestUnMarshalling),
    //                 null);
    //        }
    //    }

    //    [Log("RedemptionPoint", "UpdateRedemptionPoint", description: "RedemptionPoint/UpdateRedemptionPoint", LogType: Enums.LogType.RedemptionAccountLog)]
    //    [HttpPut("UpdateRedemptionPoint")]
    //    public async Task<ActionResult<ResultMsg>> UpdateRedemptionPoint([FromBody] UpdateRedemptionPointRequest RedemptionPoint)
    //    {
    //        var resultMsg = new ResultMsg();
    //        try
    //        {
    //            if (!RedemptionPointExists(RedemptionPoint.ID))
    //            {
    //                return resultMsg.SetResultMsg(
    //                 (int)ResultCode.UserNotFound,
    //                 HelperUtility.GetDescription(ResultCode.UserNotFound),
    //                 null);
    //            }
               
    //            var oldProductIdList = await _db.FrIpRedemptionPointProducts.Where(x => x.RedemptionPointId == RedemptionPoint.ID).Select(x=>x.ProductId).ToListAsync();

    //            var addList = RedemptionPoint.ProductIds.Except(oldProductIdList).ToList();
    //            var delList = oldProductIdList.Except(RedemptionPoint.ProductIds).ToList();
    //            var addResult = new List<FrIpRedemptionPointProduct>();
    //            var delResult = _db.FrIpRedemptionPointProducts.Where(x=> delList.Contains(x.ProductId)).ToList();



    //            FrIpRedemptionPoint dt = await _db.FrIpRedemptionPoints.FirstOrDefaultAsync(x => x.Id == RedemptionPoint.ID);
    //            dt.Code = RedemptionPoint.Code;
    //            dt.Name = RedemptionPoint.Name;
    //            dt.Description = RedemptionPoint.Description;
    //            dt.OperationAreaId = RedemptionPoint.OperationAreaID;
    //            dt.Enable = RedemptionPoint.Enable;
    //            dt.UpdateUser = CurrentUserId;
    //            dt.UpdateDate = DateTime.Now;
    //            _db.Entry(dt).State = EntityState.Modified;



    //            foreach (var ProductId in addList)
    //            {
    //                addResult.Add(new FrIpRedemptionPointProduct()
    //                {
    //                    ProductId = ProductId,
    //                    RedemptionPointId = RedemptionPoint.ID
    //                });
    //            }

    //            await _db.FrIpRedemptionPointProducts.AddRangeAsync(addResult);
    //            _db.FrIpRedemptionPointProducts.RemoveRange(delResult);

    //            await _db.SaveChangesAsync();
    //            return resultMsg.SetResultMsg(
    //              (int)ResultCode.Success,
    //              HelperUtility.GetDescription(ResultCode.Success),
    //              null);
    //        }
    //        catch (Exception ex)
    //        {
    //            _logger.LogError("RedemptionPoint/UpdateRedemptionPoint Error:" + ex.Message);
    //            return resultMsg.SetResultMsg(
    //             (int)ResultCode.ErrorOnRequestUnMarshalling,
    //             HelperUtility.GetDescription(ResultCode.ErrorOnRequestUnMarshalling),
    //             null);
    //        }
    //    }


    //    [Log("RedemptionPoint", "AddRedemptionPoint", description: "RedemptionPoint/AddRedemptionPoint", LogType: Enums.LogType.RedemptionAccountLog)]
    //    [HttpPost("AddRedemptionPoint")]
    //    public async Task<ActionResult<ResultMsg>> AddRedemptionPoint([FromBody] AddRedemptionPointRequest RedemptionPoint)
    //    {
    //        var resultMsg = new ResultMsg();
    //        try
    //        {

    //            if (RedemptionPointExists(RedemptionPoint.Code))
    //            {
    //                return resultMsg.SetResultMsg(
    //                 (int)ResultCode.AccountAlreadyExist,
    //                 HelperUtility.GetDescription(ResultCode.AccountAlreadyExist),
    //                 null);
    //            }
    //            var addList = new List<FrIpRedemptionPointProduct>();
    //            DateTime NowTime = DateTime.Now;
    //            Guid Id = Guid.NewGuid();
    //            FrIpRedemptionPoint dt = new FrIpRedemptionPoint()
    //            {
    //                Id = Id,
    //                Code = RedemptionPoint.Code,
    //                Name = RedemptionPoint.Name,
    //                Description = RedemptionPoint.Description,
    //                OperationAreaId = RedemptionPoint.OperationAreaID,
    //                Enable = RedemptionPoint.Enable,
    //                CreateUser = CurrentUserId,
    //                UpdateUser = CurrentUserId,
    //                CreateDate = NowTime,
    //                UpdateDate = NowTime
    //            };
    //            var model = await _db.FrIpRedemptionPoints.AddAsync(dt);

    //            foreach (var ProductId in RedemptionPoint.ProductIds)
    //            {
    //                addList.Add(new FrIpRedemptionPointProduct() { 
    //                    ProductId = ProductId,
    //                    RedemptionPointId = Id
    //                });
    //            }

    //            await _db.FrIpRedemptionPointProducts.AddRangeAsync(addList);

    //            await _db.SaveChangesAsync();
    //            return resultMsg.SetResultMsg(
    //             (int)ResultCode.Success,
    //             HelperUtility.GetDescription(ResultCode.Success),
    //             Id);
    //        }
    //        catch (Exception ex)
    //        {
    //            _logger.LogError("RedemptionPoint/AddRedemptionPoint Error:" + ex.Message);
    //            return resultMsg.SetResultMsg(
    //             (int)ResultCode.ErrorOnRequestUnMarshalling,
    //             HelperUtility.GetDescription(ResultCode.ErrorOnRequestUnMarshalling),
    //             null);
    //        }
    //    }


    //    [Log("RedemptionPoint", "DeleteRedemptionPoint", description: "RedemptionPoint/DeleteRedemptionPoint", LogType: Enums.LogType.RedemptionAccountLog)]
    //    [HttpDelete("DeleteRedemptionPoint")]
    //    public async Task<ActionResult<ResultMsg>> DeleteRedemptionPoint([FromBody] EnableRedemptionPointRequest RedemptionPoint)
    //    {
    //        ResultMsg resultMsg = new();
    //        List<FrIpRedemptionPoint> paDt = await _db.FrIpRedemptionPoints?.Where(x => RedemptionPoint.Ids.Contains(x.Id.ToString()))?.ToListAsync();
    //        if (paDt == null || paDt.Count < 1)
    //        {
    //            return resultMsg.SetResultMsg(
    //             (int)ResultCode.NoDataFound,
    //             HelperUtility.GetDescription(ResultCode.NoDataFound),
    //             null);
    //        }
    //        DateTime nowTime = DateTime.Now;
    //        for (int i = 0; i < paDt.Count; i++)
    //        {
    //            paDt[i].IsDelete = true;
    //            paDt[i].UpdateDate = nowTime;
    //            paDt[i].UpdateUser = CurrentUserId;
    //        }
    //        await _db.SaveChangesAsync();
    //        return resultMsg.SetResultMsg(
    //            (int)ResultCode.Success,
    //            HelperUtility.GetDescription(ResultCode.Success),
    //            null);
    //    }


    //    [Log("RedemptionPoint", "EnableRedemptionPoint", description: "RedemptionPoint/EnableRedemptionPoint", LogType: Enums.LogType.RedemptionAccountLog)]
    //    [HttpPut("EnableRedemptionPoint")]
    //    public async Task<ActionResult<ResultMsg>> EnableRedemptionPoint([FromBody] EnableRedemptionPointRequest requestModel)
    //    {
    //        ResultMsg resultMsg = new();
    //        var accountList = _db.FrIpRedemptionPoints.Where(x => requestModel.Ids.Contains(x.Id.ToString())).ToList();
    //        if (accountList == null || accountList.Count <= 0)
    //        {
    //            return resultMsg.SetResultMsg(
    //           (int)ResultCode.NoDataFound,
    //           HelperUtility.GetDescription(ResultCode.NoDataFound),
    //           null);
    //        }
    //        foreach (var account in accountList)
    //        {
    //            account.Enable = requestModel.Enable;
    //        }

    //        await _db.SaveChangesAsync();
    //        return resultMsg.SetResultMsg(
    //            (int)ResultCode.Success,
    //            HelperUtility.GetDescription(ResultCode.Success),
    //            null);
    //    }

    //    [NonAction]
    //    private bool RedemptionPointExists(Guid id)
    //    {
    //        return _db.FrIpRedemptionPoints.Any(e => e.Id == id);
    //    }

    //    [NonAction]
    //    private bool RedemptionPointExists(string Code)
    //    {
    //        return _db.FrIpRedemptionPoints.Any(e => e.Code == Code);
    //    }

    //    [NonAction]
    //    public string UserNameQuery(Guid id)
    //    {
    //        FrIpAdministratorAccount dt = _db.FrIpAdministratorAccounts?.FirstOrDefault(x => x.AccountId.Equals(id));
    //        return dt?.AccountName ?? "";
    //    }
    //}
}
